<?php

if (!defined('IN_XLP')) {
	exit('Access Denied');
}

/**
 * Description of menuAction
 * 订单管理
 * @author skyinter
 */
class orderAction extends commonAction {

	function __construct() {
		parent::__construct();
        parent::_checkLogin();
        G('path_mod', 2);
        $orderStateArry = array(
				20 => '<span class="bule">已取消</span>',
				30 => '<span class="yellow">求借款</span>',
				40 => '<span class="clra">申请借款</span>',
				41 => '<span class="clra">申请借条</span>',
				50 => '<span class="red">(求借款)借款中</span>',
				51 => '<span class="red">(求借款)申请还款</span>',
				60 => '<span class="clrb">(补借条)借款中</span>',
				61 => '<span class="clrc">(补借条)申请还款</span>',
				70 => '<span class="clre">已完成</span>'
		);
		$this->assign('orderStateArry' , $orderStateArry);

	}

	function _empty() {
		return $this->index(); 
	}


	public function index() {
		$page		= empty($_GET['page']) ? 1 : intval($_GET['page']);
		$limit 		= ($page - 1)*20;
		$starttime  = empty($_GET['starttime']) ? null : $_GET['starttime'];
		$endtime    = empty($_GET['endtime']) ? null : $_GET['endtime'];
		$searchtype = isset($_GET['searchtype']) ? intval($_GET['searchtype']) : null;
		$keyword	= empty($_GET['keyword']) ? null : trim($_GET['keyword']);

		//goods order_goods order 表别名 g og o

		$where = ' is_del = 0 ';
		//订单状态
		if(isset($_GET['status'])) {
			$status = intval($_GET['status']);
			$where  = " o.`order_state`= $status ";
		} else {
			$status = '';
			$where  = "o.`order_state` IN(20,30,40,41,50,51,60,61,70)";
		}

		// 0-下单时间 1-支付时间 默认下单时间
		$timetype_code = isset($_GET['timetype']) ? intval($_GET['timetype']) : 0;
		switch ($timetype_code) {
			case 0:
				$timetype = 'o.`create_time`';
				break;
			case 1:
				$timetype = 'o.`confirm_time`';
				break;
			default:
				$timetype = 'o.`create_time`';
				break;
		}

		//起始时间
		if($starttime) $where .= " AND $timetype >= ".strtotime($starttime)." ";
		if($endtime)   $where .= " AND $timetype <= ".strtotime($endtime)." ";

		//搜索字段
		if($keyword) {
			switch ($searchtype) {
				case '1':
					$where .= " AND o.`order_sn` LIKE '%".$keyword."%' ";
					break;
				// case '2':
				// 	$where .= " AND u.`name` LIKE '%".$keyword."%' ";
				// 	break;
				case '3':
					$where .= " AND o.`phone` LIKE '%".$keyword."%' ";
					break;
				default:
					break;
			}
		}

		//查询20笔订单
		$sql = "SELECT o.`id` AS oid, o.`order_sn`, o.`user_id` AS uid, o.`lender_id` AS lenid, o.`amount`,o.`order_type`,o.`order_state`,o.`create_time`, o.`due_time`, u.`name` FROM __PRE__order o LEFT JOIN __PRE__user_detail u ON o.`user_id` = u.`uid` WHERE {$where} ORDER BY o.`create_time` DESC";

		if(!isset($_GET['export'])) {
			$sql .= " LIMIT $limit,20";
		}

		$order_result = M()->query($sql);
		//z($order_result);
		
		//符合条件的全部订单数量
		$sql = "SELECT COUNT(`id`) AS total FROM __PRE__order o WHERE $where";
		$total = M()->query($sql);
		$order_total = $total[0]['total'];
		
		//遍历订单状态，看是否超出逾期 超出则修改状态
		// if(isHave($order_result)) {
		// 	foreach ($order_result as $k => &$v) {
		// 		if(isHave($v['due_time'])) {
		// 			if( TIME > $v['due_time']) {
		// 				M('order')->update(array('order_state' => 62) , array('id' => $v['oid']));
		// 				$v['order_state'] = 62;
		// 			}
		// 		}
		// 	}
		// }

		

		//所有订单id
		$order_ids = '';
		foreach ($order_result as &$_v) {
			$order_ids .= $_v['oid'].',';
			$userOne = M('user')->field('username')->where(array('uid'=>$_v['uid']))->find();
			$_v['username'] = $userOne['username'];
			$_v['lendername'] = '';
			if(isHave($_v['lenid'])){
				$userTwo = M('user')->field('username')->where(array('uid'=>$_v['lenid']))->find();
				$_v['lendername'] = $userTwo['username'];
			}
		}
		$order_ids = rtrim($order_ids, ',');
		if(empty($order_ids)) $order_ids = 0;



		//导出订单
		if(isset($_GET['export']) && $_GET['export']==1) {
			$this->export($order_result);
			exit;
		}
		//导出订单URL
		$url = parse_url(URL);
		if(isset($url['query']) && count($url['query'])) {
			$export_url = URL.'&export=1';
		} else {
			$export_url = URL.'?export=1';
		}
		$this->assign('export_url', $export_url);
		
		$url = preg_replace('/[&\?]status=\d*/', '', URL);
		if(strpos($url, '?') === false) {
			$this->assign('status_url', $url.'?status=');
		} else {
			$this->assign('status_url', $url.'&status=');
		}

		$this->assign('starttime', $starttime);
		$this->assign('endtime', $endtime);
		$this->assign('searchtype', $searchtype);
		$this->assign('keyword', $keyword);
		//下单时间or付款时间
		$this->assign('timetype', $timetype_code);
		//订单状态
		$this->assign('status', $status);
		//页码
		$this->assign('page', $page);
		//订单列表
		$this->assign('order_list', $order_result);
		//订单总数
		$this->assign('order_total', $order_total);
		$this->display();
	}


	public function orderStateBtn($state, $order_id) {
		$html = '';
		switch ($state) {
			case 0:		//订单取消
				$html = '<p><span style="color:#999">订单已取消</span></p>';
				break;
			case 10:	//未付款
				$html = '
				<p><span style="color:#36C">待买家付款</span></p>
				<p><a href="'.U("content/order/cancel_form",array('id'=>$order_id)).'" class="cancel_btn" rel="pop">取消订单</a></p>
				';
				break;
			case 20:	//已付款
				$html = '
				<p><span style="color:#F30">买家已付款</span></p>
				<p><a class="deliver_btn" href="'.U("content/order/deliver_form",array('id'=>$order_id)).'" rel="pop">发货</a></p>
				';
				break;
			case 30:	//确认为有效订单 已处理
			case 40:	//已发货
				$html = '<p><span style="color:#F30">卖家已发货</span></p>';
				break;
			case 50:	//已收货
				$html = '<p><span style="color:#F30">买家已收货</span></p>';
				break;
			case 60:	//退款已经提交
				$html = '<p><span style="color:#F30">买家申请<br>退款</span></p>';
				break;
			case 61:	//退货退款已经提交
				$html = '<p><span style="color:#F30">买家申请<br>退款退货</span></p>';
				break;
			case 62:	
				$html = '<p><span style="color:#F30">客服同意<br>退款</span></p>';
				break;
			case 63:	
				$html = '<p><span style="color:#F30">客服拒绝<br>退款</span></p>';
				break;
			case 64:	
				$html = '<p><span style="color:#F30">客服同意<br>退款退货</span></p>';
				break;
			case 65:	
				$html = '<p><span style="color:#F30">客服拒绝<br>退款退货</span></p>';
				break;
			case 70:	//已确认退款
				$html = '<p><span style="color:#F30">已退款<br>交易关闭</span></p>';
				break;
			case 71:	//已确认退货退款
				$html = '<p><span style="color:#F30">已退款退货<br>交易关闭</span></p>';
				break;
			default:
				# code...
				break;
		}
		return $html;
	}


	/*
	 * 导出csv格式订单
	 */
	private function export($orders) {
		// z($orders);
		foreach ($orders as $k => $v) {
			switch ($orders[$k]['order_state']) {
				case 0:
					$orders[$k]['state'] = '已取消';
					break;
				case 10:
					$orders[$k]['state'] = '申请借贷';
					break;
				case 20:
					$orders[$k]['state'] = '等待用户确认';
					break;
				case 30:
					$orders[$k]['state'] = '待发放';
					break;
				case 40:
					$orders[$k]['state'] = '借款中';
					break;
				case 50:
					$orders[$k]['state'] = '申请全额还款';
					break;
				case 61:
					$orders[$k]['state'] = '还款失败';
					break;
				case 62:
					$orders[$k]['state'] = '超出逾期';
					break;
				case 70:
					$orders[$k]['state'] = '还款完成';
					break;
				default:
					$orders[$k]['state'] = 'unknown';
					break;
			}
			unset($orders[$k]['order_state_btn']);
		}

		// z($orders);
		
		$order_list  = array();
		$order_title = array('借贷号','金额','借款人','联系电话','状态','申请时间');
		foreach ($orders as $k => $v) {
			$order_list[] = array(
				'order_sn'     => "\t".$v['order_sn'],
				'amount'	   => "\t".$v['amount'],
				'name'         => "\t".$v['name'],
				'phone'		   => "\t".$v['phone'],
				'state'		   => $v['state'],
				'create_time'  => "\t".date('Y-m-d H:i:s',$v['create_time'])
			);
		}

		load('csv');
		$csv = new csv();
		$csv->write($order_title, $order_list, "义借宝".date('Y-m-d'));
	}


	/*
	 * 发货表单
	 */
	public function deliver_form() {

		if(isset($_POST['order_id'])) {

			$order_id 			 = $this->_postid('order_id');
			$shipping_code 		 = $this->_post('shipping_code');
			$shipping_express_id = $this->_post('shipping_express_id');

			//发货
			$result = D('order')->deliver($order_id, $shipping_express_id, $shipping_code);

			if($result) {
				$this->JsonReturn('处理成功', null, 1);
			} else {
				$this->JsonReturn('处理失败', null, 0);
			}
		}

		//发货表单信息
		$express = D('express')->findAll();
		$this->assign('express', $express);

		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')->field('`id`,`order_sn`,`recipients`')->where(array('id'=>$order_id))->find();
		$order_goods = M('order_goods')->field('`goods_name`,`goods_num`')->where(array('order_id'=>$order_id))->findAll();

		$this->assign('order_goods', $order_goods);
		$this->assign('order', $order_info);
		$this->display();
	}

	/*
	 * 取消订单表单
	 */
	public function cancel_form() {

		if(isset($_POST['order_id'])) {
			$order_id = $this->_postid('order_id');
			$remark 	  = $this->_post('remark');
			//取消
			$result = D('order')->cancel($order_id, $remark);
			if($result) {
				$orderinfo = D('order')->info($order_id);
				$content = "您的一笔金额".$orderinfo['amount']."的借贷审核未通过,原因:{$remark}";
				$this->sendMemberMessage($orderinfo['user_id'] , $content);
				//发送微信模版消息
				$tpl_info['order_sn'] = $orderinfo['order_sn'];
				$tpl_info['amount'] = $orderinfo['amount'];
				$tpl_info['status'] = '审核失败';
				$tpl_info['name'] = D('member')->getUserRealName($orderinfo['user_id']);
				$tpl_info['openid'] = D('member')->getUserOpenid($orderinfo['user_id']);
				$tpl_info['first'] = '订单审核未通过';
				$remark = "审核失败：{$remark} 如有疑问，请拨打0570-3077780";
				D('weixin')->sendOrderMsg($tpl_info , $remark);
				$this->JsonReturn('取消成功', null, 1);
			} else {
				$this->JsonReturn('取消失败', null, 0);
			}
		}

		//取消订单表单信息
		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')->field('`id`,`order_sn`,`create_time`')->where(array('id'=>$order_id))->find();

		$this->assign('order', $order_info);
		$this->display();
	}

	/*
	 * 还款失败
	 */
	public function cancel_payment() {

		if(isset($_POST['order_id'])) {
			$order_id = $this->_postid('order_id');
			//取消
			$map['order_state'] = 61;
			$map['reason'] = $this->_post('reason');
			$result = M('order')->update($map , array('id' => $order_id));
			if($result) {
				$orderinfo = D('order')->info($order_id);
				//发送微信模版消息
				$tpl_info['order_sn'] = $orderinfo['order_sn'];
				$tpl_info['amount'] = $orderinfo['amount'];
				$tpl_info['status'] = '审核失败';
				$tpl_info['name'] = D('member')->getUserRealName($orderinfo['user_id']);
				$tpl_info['openid'] = D('member')->getUserOpenid($orderinfo['user_id']);
				$tpl_info['first'] = '对不起，您的申请审核失败';
				$remark = "审核失败：{$map['reason']} 如有疑问，请拨打0570-3077780";
				D('weixin')->sendOrderMsg($tpl_info , $remark);


				$this->JsonReturn('操作成功', null, 1);
			} else {
				$this->JsonReturn('操作失败', null, 0);
			}
		}

		//取消订单表单信息
		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')->field('`id`,`order_sn`,`create_time`')->where(array('id'=>$order_id))->find();

		$this->assign('order', $order_info);
		$this->display();
	}

	/*
	 * 退款表单
	 */
	public function refund_form() {

		if(isset($_POST['order_id'])) {
			$order_id = $this->_postid('order_id');
			$agree 	  = $this->_postid('agree');
			$note	  = $this->_post('note');

			//客服处理退款
			$result = D('return')->service_refund($order_id, $agree, admin::$adminInfo['id'], $note);

			if($result) {
				$this->JsonReturn('处理成功', null, 1);
			} else {
				$this->JsonReturn('处理失败', null, 0);
			}
		}

		//退款订单表单信息
		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')
			->field('`id`,`order_sn`,`refund_time`,`refund_amount`,`recipients`')
			->where(array('id'=>$order_id))
			->find();

		//退款商品
		$refund_goods = M('order_goods')
			->field('`goods_name`,`goods_num`,`goods_refund`')
			->where("`order_id`={$order_info['id']} AND `goods_refund`>0")
			->findAll();

		//退款原因
		$refund = M('return_log')
			->field('`return_msg`')
			->where(array('order_id'=>$order_id))
			->find();

		$this->assign('order', $order_info);
		$this->assign('refund_goods', $refund_goods);
		$this->assign('refund_reason', $refund['return_msg']);
		$this->display();
	}

	/*
	 * 退货表单
	 */
	public function return_form() {

		if(isset($_POST['order_id'])) {
			$order_id = $this->_postid('order_id');
			$agree 	  = $this->_postid('agree');
			$note	  = $this->_post('note');
			
			//客服处理退货
			$result = D('return')->service_return($order_id, $agree, admin::$adminInfo['id'], $note);

			if($result) {
				$this->JsonReturn('处理成功', null, 1);
			} else {
				$this->JsonReturn('处理失败', null, 0);
			}
		}

		//退货订单表单信息
		$order_id 	 = $this->_getid('id');
		$order_info  = M('order')
			->field('`id`,`order_sn`,`refund_time`,`refund_amount`,`return_amount`,`recipients`')
			->where(array('id'=>$order_id))
			->find();

		//退货商品
		$return_goods = M('order_goods')
			->field('`goods_name`,`goods_num`,`goods_returnnum`,`goods_refund`')
			->where("`order_id`={$order_info['id']} AND `goods_returnnum`>0")
			->findAll();

		//退货原因
		$refund = M('return_log')
			->field('`return_msg`')
			->where(array('order_id'=>$order_id))
			->find();

		$this->assign('order', $order_info);
		$this->assign('return_goods', $return_goods);
		$this->assign('return_reason', $refund['return_msg']);
		$this->display();
	}



	/**
	 * 订单详情
	 */
	public function info(){
		$id = $this->_get('id');
		if($id){
			$info 	= D('order')->info($id);

			//超出逾期，计算超出时间
			// if($info['order_state'] == 62) {
			// 	$due_time = $info['due_time'];
			// 	$now_time = TIME;//TIME;
			// 	$diff_days = round(($now_time - $due_time)/86400)+1;
			// 	//计算超出逾期利息
			// 	$setting = F('weixin/setting'); //获取利率配置
			// 	$over_rate = $setting['basic_setting']['over_rate'];
			// 	$over_interest = $info['amount'] * ($over_rate/100) * $diff_days;
			// 	$this->assign(array('diff_days'=>$diff_days , 'over_interest' => $over_interest));
			// }
			$userOne = D('member')->getUserRealName($info['user_id']);
			$info['name'] = $userOne['username'];
			$info['phone'] = $userOne['phone'];
			$info['lender'] = '';
			$info['lender_phone'] = '';
			if(isHave($info['lender_id'])){
				$userTwo = D('member')->getUserRealName($info['lender_id']);
				$info['lender'] = $userTwo['username'];
				$info['lender_phone'] = $userTwo['phone'];
			}
			$data_list = M('order_interest')->where(array('order_id' => $id))->findAll();
			$lxStatusArray = array(
				0  => "<span class='red'>未还</span>",
				3  => "<span class='yellow'>待审核</span>",
				5  => "<span class='clrc'>初审失败</span>",
				10 => "<span class='green'>等待财务审核</span>",
				15 => "<span class='clrc'>复审失败</span>",
				20 => "<span class='clre'>已还</span>"
			);

			$this->assign('info', $info);
			// $this->assign('operate_btn' , $this->getOperateBtn($info['order_state'] , $info['id']));
			$this->assign(array('data_list' => $data_list , 'lxStatusArray'=> $lxStatusArray));
			$this->display();
		}else{
			return $this->index();
		}
	}



	//流水支付列表 add by hsisme
	public function paylog() {
	 	$title = $this->_get('q');
        $p = $this->_getid('p', 1);
        $where[1] = 1;
        if ($title) {
            $where['LIKE'] = array('out_trade_no' => parent::safeSearch($title));
        }
		$rs = M('unipay_log')->field("`out_trade_no`,`pay_id`,`transaction_id`,`total_fee`,`create_time`")->where($where)->page($p)->order('time_end desc')->findAll();
        if(isHave($rs)){
        	foreach ($rs as &$v) {
        		$orderInfo = M('order')->field("user_id")->where(array('order_sn'=>$v['out_trade_no']))->find();
        			 $user = M('user')->field("username")->where(array('uid'=>$orderInfo['user_id']))->find();
             	$v['username'] = $user['username'] ? $user['username'] : '';
    		}	
        }	
		$this->assign(array('rs' => $rs, 'p' => $p, 'total' => M('unipay_log')->getTotal()));
        $this->display();
	}



	public function paydelete() {
		$id = $this->_postid('id',0);
		if(!isHave($id)){
			$this->JsonReturn('参数丢失');
		}
		if(M('unipay_log')->delete(array('pay_id'=>$id))){
			$this->JsonReturn('ok',null,1);
		}else{
			$this->JsonReturn('操作失败');
		}
	}



	/**
	 * 获取借贷可执行操作
	 */
	public function getOperateBtn($order_state = 0,$orderid = 0){
		$operate_btn = '';
		switch ($order_state) {
			case '10':
				$operate_btn = '<a href="'.U('order/cancel_form',array('id'=>$orderid)).'" class="cancel_btn" rel="pop">取消借贷</a> <a href="javascript:;" onclick="confirmForm('.$orderid.' , 20)" class="return_btn" >确认借贷</a> ';
				break;
			case '30':
				if(admin::$adminInfo['groupid'] == 2){ 
					$operate_btn = '<a href="'.U('order/cancel_form',array('id'=>$orderid)).'" class="cancel_btn" rel="pop">取消借贷</a> <a href="javascript:;" onclick="confirmForm('.$orderid.' , 40)" class="return_btn" >发放借贷</a> ';
				}
				break;
			case '50':
				if(admin::$adminInfo['groupid'] == 2){ 			
					$operate_btn = '<a href="'.U('order/cancel_payment', array('id' => $orderid)).'" class="cancel_btn" rel="pop">还款失败</a> <a href="javascript:;" onclick="confirmForm('.$orderid.' , 70)" class="return_btn">还款完成</a>';
				}
				break;
			case '62':
				$operate_btn = '<a href="javascript:;" onclick="confirmForm('.$orderid.' , 70)" class="return_btn">还款完成</a>';
				break;		
			default:
				break;
		}
		return $operate_btn;
	}



	public function change_order_status() {
		$orderid = $this->_postid('id');
		$status = $this->_postid('status');
		if(!isHave($orderid) || !isHave($status)) {
			$this->JsonReturn('参数丢失');
		}
		$data = array('order_state' => $status );
		if($status == 70) {
			$data['finish_time'] = TIME;
		}
		$result = M('order')->update($data,array('id'=>$orderid));
		if($result) {
			$setting = F('weixin/setting');
			$orderinfo = D('order')->info($orderid);
			if($status == 40) { //发放借款，默认插入10期的利息,头期利息默认被扣除
				$rs = D('order')->addInterestRecord($orderid);
				$content = "恭喜您的一笔借款金额 <b>￥".intval($orderinfo['amount'])."</b> 已发放，请核对是否到账";
				$this->sendMemberMessage($orderinfo['user_id'] , $content);
				//发送微信模版消息
				$tpl_info['order_sn'] = $orderinfo['order_sn'];
				$tpl_info['amount'] = $orderinfo['amount'];
				$tpl_info['status'] = '已发放';
				$tpl_info['name'] = D('member')->getUserRealName($orderinfo['user_id']);
				$tpl_info['openid'] = D('member')->getUserOpenid($orderinfo['user_id']);
				$tpl_info['first'] = '恭喜，您的借款已到账';
				$remark = "请核对是否到账，届时按时还款，保持良好信用。";
				D('weixin')->sendOrderMsg($tpl_info , $remark);
				//是否存在上级会员,存在则赠送佣金积分
				$invite_uid = D('member')->getParentUid($orderinfo['user_id']);
				if(isHave($invite_uid)) {
					$borrowCredit = $setting['basic_setting']['borrow_credit'];
					if(M('user')->where(array('uid' => $invite_uid))->setInc('credit' , $borrowCredit)){
						$member_name = D('member')->getUserRealName($orderinfo['user_id']);
						$content = "您的队员：{$member_name} 成功借到一笔借款，恭喜您成功获得<b>".$borrowCredit."</b>佣金积分";
						$this->sendMemberMessage($invite_uid , $content);
						
						//更新积分日志
						$_data['uid'] = $invite_uid;
						$_data['act'] = 1;
						$_data['credit'] = $borrowCredit;
						$_data['type'] = 1;
						$_data['content'] = "{$member_name}:借款成功";
						$_data['infotime'] = TIME;
						M('event_credit_log')->insert($_data);
					}
				}
			}

			if($status == 20) { //发送用户信息
				$content = "恭喜您获得 ". intval($orderinfo['amount']) ." 额度，请点击“<b>查看详情</b>”继续完成借款操作。";
				$url = U('weixin/order/uploadiou',array('orderid'=>$orderid));
				$this->sendMemberMessage($orderinfo['user_id'] , $content , $url);
				//发送微信模版消息
				$tpl_info['order_sn'] = $orderinfo['order_sn'];
				$tpl_info['amount'] = $orderinfo['amount'];
				$tpl_info['status'] = '已审核';
				$tpl_info['name'] = D('member')->getUserRealName($orderinfo['user_id']);
				$tpl_info['openid'] = D('member')->getUserOpenid($orderinfo['user_id']);
				$tpl_info['first'] = '订单通过初审';
				$remark = "审核成功，详情请点进进入个人中心右上角个人消息，填写收款账号并上传借条。";
				D('weixin')->sendOrderMsg($tpl_info , $remark);
			}


			if($status == 70) { //还清一笔借款, 获得信用积分
				$esteem_credit = round(($orderinfo['amount'] * $setting['basic_setting']['esteem_credit_rate'])/100);
				M('user')->where(array('uid' => $orderinfo['user_id']))->setInc('esteem_credit',$esteem_credit);
				//发送微信模版消息
				$tpl_info['order_sn'] = $orderinfo['order_sn'];
				$tpl_info['amount'] = $orderinfo['amount'];
				$tpl_info['status'] = '已完成';
				$tpl_info['name'] = D('member')->getUserRealName($orderinfo['user_id']);
				$tpl_info['openid'] = D('member')->getUserOpenid($orderinfo['user_id']);
				$tpl_info['first'] = '恭喜，您已成功还清一笔借款';
				$remark = "如有疑问，请拨打0570-3077780";
				D('weixin')->sendOrderMsg($tpl_info , $remark);
				//是否存在上级会员,存在则赠送佣金积分
				$invite_uid = D('member')->getParentUid($orderinfo['user_id']);
				if(isHave($invite_uid)) {
					$borrowCredit = $setting['basic_setting']['borrow_credit'];
					if(M('user')->where(array('uid' => $invite_uid))->setInc('credit' , $borrowCredit)){
						$member_name = D('member')->getUserRealName($orderinfo['user_id']);
						$content = "您的队员：{$member_name} 成功还清一笔借款，恭喜您成功获得<b>".$borrowCredit."</b>佣金积分";
						$this->sendMemberMessage($invite_uid , $content);
						//更新积分日志
						$_data['uid'] = $invite_uid;
						$_data['act'] = 1;
						$_data['credit'] = $borrowCredit;
						$_data['type'] = 1;
						$_data['content'] = "{$member_name}:还款成功";
						$_data['infotime'] = TIME;
						M('event_credit_log')->insert($_data);
					}
				}
			}

			$this->JsonReturn('ok' , null , 1);
		}else{
			$this->JsonReturn('操作失败');
		}
	}


	public function changeInterestStatus() {
		$id = $this->_postid('id');
		$status = $this->_post('status');
		$islast = $this->_post('islast');
		$data ['status'] = $status;
		if($status == 20) $data['finish_time'] = TIME;
		M('order_interest')->update($data , array('id' => $id));
		//最后一期自动改订单状态为完成
		if($islast && $status == 20) {
			$orderid = $this->_postid("orderid");
			$map['order_state'] = 70;
			$map['finish_time'] = TIME;
			M('order')->update($map , array('id' => $orderid));
		}
		$this->JsonReturn('ok',null,1);
	}

	/**
	 * 订单分析
	 */
	public function stat(){
		$this->display();
	}


	/*
	 * 订单图表
	 */
	public function chart() {
		//图表title
		$title = '';

		if( !isset($_GET['starttime']) && !isset($_GET['endtime']) ) {
			$today     = date('Y-m-d',time());
			$starttime = strtotime($today);
			$endtime   = $starttime + 24*3600;
			$title	   = $today.'的商品销量';
		} else {
			$starttime = isset($_GET['starttime']) ? strtotime($this->_get('starttime')) : null;
			$endtime   = isset($_GET['endtime']) ? strtotime($this->_get('endtime')) : null;
			if(!$starttime) {
				$title = date('Y-m-d H:i:s',$endtime).'之前的商品销量';
			} else if(!$endtime) {
				$title = date('Y-m-d H:i:s',$starttime).'至今的商品销量';
			} else {
				$title = date('Y-m-d H:i:s',$starttime).'~'.date('Y-m-d H:i:s',$endtime).'的商品销量';
			}
		}

		$where = ' 1=1 ';
		if($starttime) $where .= " AND `payment_time`>=$starttime ";
		if($endtime)   $where .= " AND `payment_time`<=$endtime ";

		$sql = "SELECT og.`goods_name`, SUM(og.`goods_num`) goods_sum
				FROM __PRE__order_goods og, __PRE__order o
				WHERE og.`order_id`=o.`id`
				AND o.`payment_time`<>0
				AND $where
				GROUP BY og.`goods_id`
				ORDER BY goods_sum";

		$result = M()->query($sql);
		
		$goods_sum  = '';
		$goods_name	= '';

		foreach ($result as $v) {
			$temp = preg_replace('/\s/', '', addslashes($v['goods_name']));
			$goods_name .= "'".$temp."',";
			$goods_sum  .= $v['goods_sum'].',';
		}

		$this->assign('starttime', $this->_get('starttime'));
		$this->assign('endtime', $this->_get('endtime'));
		$this->assign('title', $title);
		$this->assign('goods_sum', $goods_sum);
		$this->assign('goods_name', $goods_name);
		$this->display();
	}

	/**
	 * 配送公司列表
	 */
	protected function express(){
		$express = D('express')->findAll();
		$this->assign('express', $express);
		return $express;
	}

	/*
	 * 测试发货接口
	 */
	public function test_deliver() {
		$order_id = $_GET['id'];
		$result = D('order')->wxDelivery($order_id);
		z($result);
	}

	/*
	 * 查询物流信息
	 */
	public function check_express() {
		//订单id
		$order_id = $this->_getid('id');

		$sql = "SELECT e.`e_name`,o.`shipping_code`,o.`user_id`
				FROM __PRE__express e, __PRE__order o
				WHERE o.`id`={$order_id} AND e.`id`=o.`shipping_express_id`";
		$rs = M()->query($sql);
		$rs = $rs[0];

		if($rs) {
			//跳转快递100查询快递
			$url = 'http://m.kuaidi100.com/index_all.html?'
					.'type='.$rs['e_name']
					.'&postid='.$rs['shipping_code'];
			header("Location: $url");
		} else {
			showError('Sorry, 暂时没有查到您的物流信息');
		}

	}
}
